package com.gitee.exporttool.command;

import com.gitee.exporttool.mapper.ExportMapper;
import com.gitee.exporttool.util.EasyExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import picocli.CommandLine;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Callable;

@Slf4j
@Component
@CommandLine.Command(name = "export", mixinStandardHelpOptions = true, version = "1.0",
    description = "导出相关的命令工具后缀默认为xlsx")
public class ExportCommand implements Callable<Integer> {

    @Autowired
    private ExportMapper exportMapper;

    @CommandLine.Option(names = {"-f", "--file"}, required = true, description = "sql文件路径")
    private String sqlPath;

    @CommandLine.Option(names = {"-s", "--size"}, description = "分页大小默认1000", defaultValue = "1000")
    private Integer pageSize;

    @CommandLine.Option(names = {"-c", "--count"}, description = "sheet数量默认1000000", defaultValue = "1000000")
    private Integer sheetCount;

    @CommandLine.Option(names = {"-o", "--output"}, description = "输出文件名", defaultValue = "1")
    private String outFileName;

    @Override
    public Integer call() throws Exception {
        if (null != pageSize) {
            EasyExcelUtil.setPageSize(pageSize);
        }

        if (null != sheetCount) {
            EasyExcelUtil.setSheetSize(sheetCount);
        }

        if (StringUtils.isNotBlank(outFileName)) {
            EasyExcelUtil.setFileName(outFileName);
        }

        if (StringUtils.isNotBlank(sqlPath)) {
            log.info("sqlPath:{}", sqlPath);
            try {
                String sql = FileUtils.readFileToString(new File(sqlPath), StandardCharsets.UTF_8);
                if (StringUtils.isNotBlank(sql)) {
                    log.info("sql:{}", sql);
                    sql = sql.trim();
                    EasyExcelUtil.writeExcel(this.exportMapper, sql);
//                    IPage<LinkedHashMap<String, Object>> page = this.exportMapper.selectMap(new Page<>(1, pageSize), sql);
//                    log.info("sql执行分页结果: 页大小: {}, 当前页:{}, 总页数:{}, 总条数: {}", page.getSize(), page.getCurrent(), page.getPages(), page.getTotal());
//                    List<LinkedHashMap<String, Object>> resutl = page.getRecords();
//                    EasyExcelUtil.writeExcel(resutl, "");
//                    log.info("sql执行结果:{}", JSON.toJSONString(resutl));
                }
            } catch (Exception e) {
                log.error("读取sql文件失败", e);
            }
        }
        return 0;
    }
}
